<template>
  <div>
    <sticky-top>
      <div class="title">
        <span>{{ isCreate ? '创建监控设备' : '更新监控设备' }}</span>
        <span class="back" @click="back"> <i class="iconfont icon-fanhui"></i> 返回 </span>
        <el-divider></el-divider>
      </div>
    </sticky-top>
    <div class="container">
      <div class="wrap">
        <el-row>
          <el-col :lg="16" :md="20" :sm="24" :xs="24">
            <el-form :model="form" status-icon ref="form" label-width="100px" @submit.native.prevent>
              <el-form-item label="设备名称" prop="md_name">
                <el-input size="medium" v-model="form.md_name" placeholder="请填写设备名称"></el-input>
              </el-form-item>
              <el-form-item label="所在楼栋" prop="building_name">
                <el-autocomplete
                  clearable
                  @focus="loadBuildingSuggestions"
                  popper-class="my-autocomplete"
                  class="inline-input"
                  v-model="form.building_name"
                  :fetch-suggestions="queryBuildingSearch"
                  placeholder="请选择所在楼栋"
                  @select="handleBuildingSelect"
                >
                  <template slot-scope="{ item }">
                    <span class="id">{{ item.id }}</span>
                    <span class="name">{{ item.name }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>

              <el-form-item  label="所在房间" prop="room_name">
                <el-autocomplete
                  clearable
                  @focus="loadRoomSuggestions"
                  popper-class="my-autocomplete"
                  class="inline-input"
                  v-model="form.room_name"
                  :fetch-suggestions="queryRoomSearch"
                  placeholder="请选择所在房间"
                  @select="handleRoomSelect"
                  @change="loadRoomSuggestions"
                >
                  <template slot-scope="{ item }">
                    <span class="id">{{ item.id }}</span>
                    <span class="name">{{ item.name }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>

              <el-form-item label="设备状态" prop="md_state">
                <el-input size="medium" v-model="form.md_state" placeholder="请填写设备状态"></el-input>
              </el-form-item>
              <el-form-item label="规格型号" prop="md_model">
                <el-input size="medium" v-model="form.md_model" placeholder="请填写规格型号"></el-input>
              </el-form-item>
              <el-form-item label="生产厂家" prop="md_maker">
                <el-input size="medium" v-model="form.md_maker" placeholder="请填写生产厂家"></el-input>
              </el-form-item>
              <el-form-item label="出厂编号" prop="md_maker_num">
                <el-input size="medium" v-model="form.md_maker_num" placeholder="请填写出厂编号"></el-input>
              </el-form-item>

              <el-form-item label="入账日期" prop="md_input_date">
                <el-date-picker
                  v-model="form.md_input_date"
                  align="right"
                  type="date"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>

              <el-form-item label="启用日期" prop="md_use_date">
                <el-date-picker
                  v-model="form.md_use_date"
                  align="right"
                  type="date"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
<!--              <el-form-item label="入账日期" prop="md_input_date">-->
<!--                <el-input size="medium" v-model="form.md_input_date" placeholder="请填写入账日期"></el-input>-->
<!--              </el-form-item>-->
<!--              <el-form-item label="启用日期" prop="md_use_date">-->
<!--                <el-input size="medium" v-model="form.md_use_date" placeholder="请填写启用日期"></el-input>-->
<!--              </el-form-item>-->


<!--              <el-form-item label="是否有效" prop="is_use">-->
<!--                <el-switch-->
<!--                  style="display: block"-->
<!--                  active-color="#13ce66"-->
<!--                  v-model="form.is_use"-->
<!--                  inactive-color="#ff4949"-->
<!--                  active-text="有效"-->
<!--                  inactive-text="无效"-->
<!--                >-->
<!--                </el-switch>-->
<!--                <el-input size="medium" v-model="form.is_use" placeholder="请填写部门是否有效"></el-input>-->
<!--              </el-form-item>-->
              <el-form-item class="submit">
                <el-button
                  v-permission="{ permission: ['创建监控设备', '更新监控设备'], type: 'disabled' }"
                  type="primary"
                  @click="submitForm('form')"
                >保 存</el-button
                >
                <el-button @click="resetForm('form')">重 置</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>

import MonitoringDevices from '@/model/ag_monitoring_devices'
import Building from '@/model/ag_building'
import Room from '@/model/ag_room'

export default {
  props: {
    isCreate: {
      type: Boolean,
      default: false,
    },
    deviceId: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      form: {
        md_name:'',
        room_id:'',
        room_name:'',
        building_id:'',
        building_name: '',
        md_model:'',
        md_maker:'',
        md_maker_num: '',
        md_input_date: '',
        md_use_date: '',
        md_state: '',
      },
      buildings:[],
      //通过楼栋id查所属房间
      searchId:'',
      rooms:[],
      rules: {
        minWidth: 100,
        minHeight: 100,
        maxSize: 5,
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
    }
  },
  async mounted() {
    if (!this.isCreate) {
      // const res =  Unit.getUnit(this.unitId)
      const res = await MonitoringDevices.getMonitoringDevice(this.deviceId)
      this.form = res
      this.searchId=this.form.building_id
    }
  },
  methods: {
    // eslint-disable-next-line
    async submitForm(formName) {
      const postData = { ...this.form }
      let res
      if (this.isCreate) {
        res = await MonitoringDevices.addMonitoringDevices(postData)
      } else {
        res = await MonitoringDevices.editMonitoringDevices(this.deviceId, postData)
      }
      this.$message.success(`${res.message}`)
      this.$emit('editClose')
      // if (res.code < window.MAX_SUCCESS_CODE) {
      //   this.$message.success(`${res.message}`)
      //   // this.resetForm(formName)
      //   this.$confirm('是否返回上一页', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning',
      //   }).then(async () => {
      //     this.$emit('editClose')
      //   })
      // }
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    back() {
      this.$emit('editClose')
    },

    async loadBuildingSuggestions() {
      if (this.buildings.length > 0) {
        return
      }
      try {
        this.buildings = await Building.getBuildings()
        if (this.buildings.length === 0) {
          this.$message.error('暂无楼栋信息，请先添加')
        }
      } catch (error) {
        this.$message.error('获取楼栋信息失败')
        console.error(error)
      }
    },
    async loadRoomSuggestions() {
      if (this.rooms.length > 0) {
        return
      }
      try {
        this.rooms = await Room.getDetailByBuilding(this.searchId)
        if (this.rooms.length === 0) {
          this.$message.error('暂无房间信息，请先添加')
        }
      } catch (error) {
        this.$message.error('获取房间信息失败')
        console.error(error)
      }
    },

    queryBuildingSearch(queryString, cb) {
      // eslint-disable-next-line
      const suggestions = this.buildings
      const results = queryString ? suggestions.filter(this.createCategoryFilter(queryString)) : suggestions
      cb(results)
    },

    queryRoomSearch(queryString, cb) {
      // eslint-disable-next-line
      const suggestions = this.rooms
      const results = queryString ? suggestions.filter(this.createCategoryFilter(queryString)) : suggestions
      cb(results)
    },

    // querySpecKeySearch(queryString, cb) {
    //   // eslint-disable-next-line
    //   const suggestions = this.buildings
    //   const results = queryString ? suggestions.filter(this.createCategoryFilter(queryString)) : suggestions
    //   cb(results)
    // },
    createCategoryFilter(queryString) {
      // eslint-disable-next-line
      return suggestion => {
        return suggestion.name.toLowerCase()
          .indexOf(queryString.toLowerCase()) === 0
      }
    },
    // createSkuFilter(queryString) {
    //   // eslint-disable-next-line
    //   return suggestion => {
    //     return suggestion.title.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    //   }
    // },
    handleBuildingSelect(item) {
      this.form.building_name = item.name
      this.form.building_id = item.id
      this.rooms=[]
      this.searchId = item.id
    },

    handleRoomSelect(item) {
      this.form.room_name = item.name
      this.form.room_id = item.id
    },

  },
}
</script>

<style lang="scss" scoped>
.el-divider--horizontal {
  margin: 0;
}

.container {
  .title {
    height: 59px;
    line-height: 59px;
    color: $parent-title-color;
    font-size: 16px;
    font-weight: 500;
    text-indent: 40px;

    .back {
      float: right;
      margin-right: 40px;
      cursor: pointer;
    }
  }

  .wrap {
    padding: 20px;
  }

  .submit {
    float: left;
  }
}

.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;
    display: inline-flex;
    align-content: space-around;
    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .id {
      margin-right: 15px;
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>
